#include "CMap.h"
#include <stdio.h>

CMap::CMap(char *path)
{
	bmp_tiles[0] = (HBITMAP)LoadImage(NULL, "data/tiles/tile_gd.bmp" ,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	bmp_tiles[1] = (HBITMAP)LoadImage(NULL, "data/tiles/tile_dg.bmp" ,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	bmp_tiles[2] = (HBITMAP)LoadImage(NULL, "data/tiles/tile_rd.bmp" ,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	bmp_tiles[3] = (HBITMAP)LoadImage(NULL, "data/tiles/tile_wd.bmp" ,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);

	FILE *f = fopen(path, "rb");

	if (!f)
		return;

	unsigned char v[2];

	fread(v,2,1,f);

	mapW = v[0];
	mapH = v[1];

	mapData = new char[mapW * mapH];

	fread(mapData, mapW * mapH, 1, f);
	fclose(f);
}

void CMap::paint(HDC dc, int px, int py)
{
	HDC memDC = CreateCompatibleDC(dc);

	int lastImg = -1;

	for (int i=0;i<MAP_VISY;i++)
	{
		for (int j=0;j<MAP_VISX;j++)
		{
			int p = getTile(j+px,i+py);

			if (p != lastImg)
			{
				lastImg = p;

				if (lastImg<4)
					SelectObject(memDC, bmp_tiles[lastImg]);
			}

			BitBlt(dc, j*32, i*32, 32,32, memDC, 32,32,SRCCOPY);
		}
	}

	DeleteObject(memDC);
}

int CMap::getTile(int x, int y)
{
	return mapData[y*mapW + x];
}

int CMap::getWidth()
{
	return mapW;
}

int CMap::getHeight()
{
	return mapH;
}
